package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ApUserSearchServiceImpl apUserSearchService;
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        //如果关键字为空 直接返回一个null
        if (StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//  根据标题模糊查询   match分词  term不分词
        QueryBuilder query = QueryBuilders.matchQuery("title",dto.getSearchWords());
//  按照发布时间倒序排序
//  分页查询
        Pageable pageable = PageRequest.of(dto.getPage().intValue()-1,dto.getSize(), Sort.by(Sort.Direction.DESC,"publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(query,pageable);

        //        保存用户的搜索记录（采用异步的方式）
        apUserSearchService.saveUserSearch(UserThreadLocalUtil.get().getUserId(),dto.getEquipmentId(),dto.getSearchWords());

        return ResponseResult.okResult(searchPage.getContent());

    }
}
